<template>
<div class="containerWrap">
  <el-container class="container">
    <el-aside class="appTree" width="200px">
      <app-tree v-bind:tree-data="treeData"
                title='权限树'
                v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main class="rightMain">
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              权限名称：<el-input size="small" placeholder="请输入角色名称" v-model="queryData.name" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              <el-button size="small" @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main class="tableMain">
          <app-table :page-data="pageData"
                     :table-columns="tableColumns"
                     v-on:currentChange="handleCurrentChange"
                     v-on:handleCheckedRows="handleCheckedRows" />
        </el-main>
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible"  :close-on-click-modal="false" :before-close="close" class="dialog_style">
          <div class="formWrapper">
            <el-form class="formMain" :model="formData"
                    :rules="rules"
                    ref="formData"
                    label-width="90px"
                    size="small">
              <el-divider content-position="left">基本信息</el-divider>
              <el-row :gutter="15">
                <el-col :span="12">
                  <el-form-item label="上级菜单：" prop="parentIdArr">
                    <div class="block">
                      <el-cascader placeholder="请选择" style="width:100%"
                      :options="treeOption" filterable clearable
                      :props="gridIdProps"
                      :show-all-levels="false"
                      v-model="formData.parentIdArr">
                      </el-cascader>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="权限名：" prop="name">
                    <el-input v-model="formData.name" placeholder="权限名"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="权限编码：" prop="code">
                    <el-input v-model="formData.code" placeholder="权限编码"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="路径：" prop="uri">
                    <el-input v-model="formData.uri" placeholder="权限编码"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="权限类型：" prop="type">
                     <el-select filterable style="width:100%" v-model="formData.type" placeholder="权限类型">
                      <el-option label="模块" value="module"></el-option>
                      <el-option label="菜单" value="menu"></el-option>
                      <el-option label="按钮" value="btn"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="按钮类型：" prop="btnType"
                  :rules="formData.type === 'btn'?[{required: true,message: '请选择按钮类型',trigger: 'blur'}]:[{required: false ,trigger: 'blur'}]">
                     <el-select filterable style="width:100%" v-model="formData.btnType" :disabled="formData.type !== 'btn'" placeholder="按钮类型">
                      <el-option v-for="(btn, index) in btnData" :key="index" :label="btn.label" :value="btn.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="查询等级：" prop="queryLevel">
                     <el-select filterable style="width:100%" v-model="formData.queryLevel" placeholder="查询等级">
                      <el-option label="当前部门" value="current"></el-option>
                      <el-option label="子部门" value="children"></el-option>
                      <el-option label="全部" value="all"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="菜单图标：" prop="icon">
                    <el-input v-model="formData.icon" placeholder="菜单图标"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="排序：" prop="displayOrder">
                    <el-input v-model="formData.displayOrder" placeholder="排序"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button size="small" @click="cancel('formData')">取 消</el-button>
              <el-button size="small" type="primary" :disabled="showOnly" @click="save('formData')">提 交</el-button>
            </div>
          </div>
        </el-dialog>
      </el-container>
    </el-main>
  </el-container>
</div>
</template>

<script>
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import AppTree from '@/components/common/AppTree'
import { getAllRegion, getAllRegionObj } from '@/utils/region'
import { createPermission, findPermission, updatePermission, deletePermission, getPermissionAllTree } from '@/http/setApi'
export default {
  data () {
    return {
      active: 1,
      mapMode: 'full',
      dialogTitle: '新增权限',
      currentSelectedRowId: '',
      showMap: false,
      showOnly: false,
      dialogFormPromise: false,
      dialogFormVisible: false,
      btnData: [],
      treeData: [],
      treeOption: [],
      currentSelectedData: [],
      formData: {},
      pageData: {},
      queryData: {},
      mapTarget: {},
      gridIdProps: {
        label: 'name',
        value: 'id',
        checkStrictly: true
      },
      tableColumns: [
        { label: 'id', prop: 'id' },
        { label: '名称', prop: 'name' },
        { label: '路径', prop: 'uri' },
        { label: '类型', prop: 'type' },
        { label: '上级菜单', prop: 'parentId', formatter: this.nameFormatter },
        { label: '上级id', prop: 'parentId' },
        { label: '排序', prop: 'displayOrder' },
        { label: '更新时间', prop: 'createTime', formatter: this.timeFormatter }
      ],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      rules: {
        name: [{
          required: true,
          message: '权限名',
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '权限编码',
          trigger: 'blur'
        }],
        uri: [{
          required: true,
          message: '路径',
          trigger: 'blur'
        }],
        queryLevel: [{
          required: true,
          message: '查询等级',
          trigger: 'change'
        }]
      }
    }
  },
  mounted () {
    this.getTableData()
    this.setBtnData()
    this.getPermissionTree()
  },
  components: {BtnGroup, AppTable, AppTree},
  methods: {
    nameFormatter (row) {
      let regionData = {}
      regionData.id = row.parentId
      regionData.items = this.treeData
      let gridIdArr = getAllRegionObj(regionData)
      if (gridIdArr && gridIdArr.length > 0) {
        return gridIdArr[gridIdArr.length - 1].name
      } else {
        return '根目录'
      }
    },
    timeFormatter (row) {
      if (row && row.createTime) {
        return this.$moment(row.createTime).format('YYYY-MM-DD')
      }
    },
    setBtnData () {
      this.btnData.push({label: '添加', value: 'post'})
      this.btnData.push({label: '修改', value: 'put'})
      this.btnData.push({label: '查看', value: 'get'})
      this.btnData.push({label: '删除', value: 'delete'})
      this.btnData.push({label: '打印', value: 'print'})
      this.btnData.push({label: '导出', value: 'educe'})
      this.btnData.push({label: '地图标注', value: 'mark'})
      this.btnData.push({label: '绘制地图', value: 'draw'})
      this.btnData.push({label: '通过', value: 'approve'})
      this.btnData.push({label: '拒绝', value: 'not_approve'})
      this.btnData.push({label: '积分变动', value: 'point_changed'})
      this.btnData.push({label: '设置授权码', value: 'set_authorizationCode'})
      this.btnData.push({label: '推荐置顶', value: 'set_distinction'})
      this.btnData.push({label: '新增字典', value: 'newDictionary'})
      this.btnData.push({label: '删除字典', value: 'delDictionary'})
      this.btnData.push({label: '修改字典', value: 'revampDictionary'})
      this.btnData.push({label: '新增字典值', value: 'createDictionaryValue'})
      this.btnData.push({label: '重置密码', value: 'resetPasswd'})
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.beforeSubmit()
          if (this.formData.id) {
            updatePermission(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.getPermissionTree()
                this.cancel(formName)
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: resp.data
                })
              }
            })
          } else {
            createPermission(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.getPermissionTree()
                this.cancel(formName)
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: resp.data
                })
              }
            })
          }
        }
      })
    },
    beforeSubmit () {
      console.log(this.formData.parentIdArr)
      if (this.formData.parentIdArr && this.formData.parentIdArr.length > 0) {
        let parentId = this.formData.parentIdArr[this.formData.parentIdArr.length - 1]
        this.$set(this.formData, 'parentId', parentId)
      }
      return true
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deletePermission(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({type: 'success', message: '删除成功'})
                this.getPermissionTree()
                this.getTableData()
                this.cancel()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    getTableData () {
      let param = this.queryData
      findPermission(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    getUnitTree () {
      findPermission().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.treeData = this.treeOption = data
        }
      })
    },
    getPermissionTree () {
      getPermissionAllTree().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.treeData = this.treeOption = data
        }
      })
    },
    btnClickCallback (callbackData) {
      this.dialogFormVisible = true
      this.showOnly = callbackData.showOnly
      this.dialogTitle = callbackData.dialogTitle
      if (callbackData.btnType === 'post') {
        this.formData = this.formData.parentIdArr ? this.formData : {}
      } else if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        let data = JSON.parse(JSON.stringify(callbackData.rows[0]))
        this.formData = data
        let regionData = {}
        regionData.id = this.formData.parentId
        regionData.items = this.treeData
        let gridIdArr = getAllRegion(regionData)
        this.$set(this.formData, 'parentIdArr', gridIdArr)
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
        this.currentSelectedRowId = rows[0].id
      } else {
        this.currentSelectedData = []
      }
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    treeClickHandle (data) {
      this.queryData.offset = 0
      this.queryData.id = data.id
      this.getTableData()
      let regionData = {}
      regionData.id = data.id
      regionData.items = this.treeData
      let gridIdArr = getAllRegion(regionData)
      this.$set(this.formData, 'parentIdArr', gridIdArr)
    },
    close (type) {
      this.dialogFormVisible = false
      this.formData = {}
      if (this.$refs['formData']) this.$refs['formData'].resetFields()
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
      if (this.$refs['formData']) this.$refs['formData'].resetFields()
    }
  }
}
</script>
<style scoped>
  .containerWrap {
    padding:10px;
    height: 100%;
    box-sizing: border-box
  }
  .container {
    height: 100%;
  }
</style>
